package com.nanbei.queue;

import java.util.Iterator;

/**
 * @ClassDescription: 环形链表的双端队列
 * @JdkVersion: 17
 * @Author: BaoShan.li
 * @Created: 2023/11/28 14:28
 */
public class LinkDeque<E> implements DequeInterface<E>,Iterable<E> {


     static class Node<E>{

        Node<E> prev;
        E value;
        Node<E> next;

        public Node(Node<E> prev, E value, Node<E> next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    Node<E> sentinel = new Node<>(null, null, null);
    int capacity;
    int size = 0;

    public LinkDeque(int capacity) {
        sentinel.next = sentinel;
        sentinel.prev = sentinel;
        this.capacity = capacity;
    }

    @Override
    public boolean offerFirst(E value) {
        if (isFull()){
            return false;
        }
        Node<E> eNode = new Node<>(sentinel, value, sentinel.next);
        sentinel.next.prev = eNode;
        sentinel.next = eNode;
        size++;
        return true;
    }

    @Override
    public boolean offerLast(E value) {
        if (isFull()){
            return false;
        }
        Node<E> eNode = new Node<>(sentinel.prev, value, sentinel);
        sentinel.prev.next = eNode;
        sentinel.prev = eNode;
        size++;
        return true;
    }

    @Override
    public E pollFirst() {
        if (isEmpty()){
            return null;
        }
        Node<E> node = sentinel.next;
        sentinel.next = node.next;
        node.next.prev = sentinel;
        size--;
        return node.value;
    }

    @Override
    public E pollLast() {
        if (isEmpty()){
            return null;
        }
        Node<E> node = sentinel.prev;
        sentinel.prev = node.prev;
        node.prev.next = sentinel;
        size--;
        return node.value;
    }

    @Override
    public E peekFirst() {
        if (isEmpty()){
            return null;
        }
        return sentinel.next.value;
    }

    @Override
    public E peekLast() {
        if (isEmpty()){
            return null;
        }
        return sentinel.prev.value;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> node = sentinel.next;

            @Override
            public boolean hasNext() {
                return node != sentinel;
            }

            @Override
            public E next() {
                E value = node.value;
                node = node.next;
                return value;
            }
        };
    }
}
